import pool from '../config/database';
export interface User {
  userId?: string;
  userIndex?: number;
  username: string;
  password: string;
  register_ip: string;
  created_at?: Date;
  updated_at?: Date;
}
export class UserModel {
  // 根据用户名查找用户
  async findByUsername(username: string): Promise<User | null> {
    const [rows] = await pool.execute('SELECT * FROM users WHERE username = ?', [username]);
    const users = rows as User[];
    return users.length > 0 ? users[0] : null;
  }

  // 创建新用户
  async create(user: Omit<User, 'userId' | 'created_at'>): Promise<string> {
    const [result] = await pool.execute(
      'INSERT INTO users (username, password, register_ip) VALUES (?, ?, ?)',
      [user.username, user.password, user.register_ip]
    );
    const insertResult = result as any;
    const [rows] = await pool.execute(
      'SELECT userId FROM users WHERE user_index = ?',
      [insertResult.insertId]
    );
    const users = rows as User[];
    return users[0]?.userId || '';
  }
  // 根据userId查找用户
  async findByUserId(userId: string): Promise<User | null> {
    const [rows] = await pool.execute(
      'SELECT userId, user_index, username, password, created_at, updated_at FROM users WHERE userId = ?',
      [userId]
    );
    const users = rows as User[];
    return users.length > 0 ? users[0] : null;
  }
  // 根据Ip查找用户
  async findByUserIp(register_ip: string): Promise<User | null> {
    const [rows] = await pool.execute(
      'SELECT userId, user_index, username, password, created_at, register_ip, updated_at FROM users WHERE register_ip = ?',
      [register_ip]
    );
    const users = rows as User[];
    return users.length > 0 ? users[0] : null;
  }
  async updateUser(user: { username: string, password: string, updated_at: string, userId: string}) {
    const res = await pool.execute(
      'UPDATE users SET username = ?, password = ?, updated_at = ? WHERE userId = ?',
      [user.username, user.password, user.updated_at, user.userId]
    );
    return res;
  }
  async updateUserPwd(user: { password: string, userId: string, updated_at: string}) {
    const res = await pool.execute(
      'UPDATE users SET password = ?, updated_at = ? WHERE userId = ?',
      [user.password, user.updated_at, user.userId]
    );
    return res;
  }
  async getUsersByUserIds(ids: string[]) {
    const [userNams] = await pool.execute(
      `SELECT username, userId, register_ip FROM users WHERE userId IN (${ ids.map(() => '?').join(',') })`,
      ids
    ) as any[];
    return userNams
  }
}